<template>
  <div id="qcResultConvertRuleDiv">
    <Breadcrumb content="质控结果转换规则" />
    <div class="bodyContent">
      <vxe-toolbar perfect>
        <template #buttons>
          <div class="smallToolTitle">仪器</div>
          <vxe-select v-model="searchForm.instrId" :filterable="true" @change="valueChangeEvent">
            <vxe-option v-for="instr in instrList" :key="instr.id" :value="instr.id" :label="instr.instrName"></vxe-option>
          </vxe-select>

          <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="rloading" @click="findConvertRuleList"></vxe-button>
          <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" @click="addConvertRule"></vxe-button>
          <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="saveConvertRuleList"></vxe-button>
          <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteConvertRule"></vxe-button>
        </template>
      </vxe-toolbar>

      <div class="tableBox">
        <vxe-table ref="convertRuleTableRef" class="mytable-scrollbar" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true }" :data="ruleList" :loading="rloading" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
          <vxe-column type="checkbox" width="30"></vxe-column>

          <vxe-column field="itemDictId" title="规则应用对象" width="200" :edit-render="{ autofocus: '.vxe-input--inner' }">
            <template #default="{ row }">
              <span>{{ getItemDictDesc(row) }}</span>
            </template>

            <!-- { field: '', title: '', type: 'checkbox', width: '30px' }, -->
            <template #edit="{ rowIndex }">
              <SelectDataGrid :url="'/lis/lab/item/findLabItemDictAndAllListByInstr'" :column="[
                  { field: 'itemNo', title: '项目代码' },
                  { field: 'itemEnCode', title: '英文缩写' }, //列标题
                  { field: 'itemNa', title: '报告项目名称' },
                  { field: 'inputCode', title: '助记符' }
                ]" :searchParam="{ instrId: searchForm.instrId }" :isPage="false" @SelectCellClick="
                  (e) => {
                    selectRow(e, rowIndex);
                  }
                " :showField="'itemName'"></SelectDataGrid>
            </template>
          </vxe-column>

          <vxe-column field="seq" title="优先级" width="150" :edit-render="{}">
            <template #edit="{ row, rowIndex, column }">
              <vxe-input v-model="row.seq" type="number"></vxe-input>
            </template>
          </vxe-column>

          <vxe-column field="conKind" title="条件" width="200" :edit-render="{}">
            <template #default="{ row }">
              <span>{{ formatCommon(conKindList, row.conKind) }}</span>
            </template>
            <template #edit="{ row, rowIndex, column }">
              <!-- 选择字典  -->
              <vxe-select v-model="row.conKind">
                <vxe-option v-for="hobj in conKindList" :key="hobj.id" :value="hobj.code" :label="hobj.name"></vxe-option>
              </vxe-select>
            </template>
          </vxe-column>

          <vxe-column field="conParm1" title="条件取值1" width="200" :edit-render="{}">
            <template #edit="{ row, rowIndex, column }">
              <vxe-input v-model="row.conParm1" placeholder="" type="text"></vxe-input>
            </template>
          </vxe-column>

          <vxe-column field="transKind" title="处理方式" width="200" :edit-render="{}">
            <template #default="{ row }">
              <span>{{ formatCommon(transKindList, row.transKind) }}</span>
            </template>
            <template #edit="{ row, rowIndex, column }">
              <!-- 选择字典  -->
              <vxe-select v-model="row.transKind">
                <vxe-option v-for="hobj in transKindList" :key="hobj.id" :value="hobj.code" :label="hobj.name"></vxe-option>
              </vxe-select>
            </template>
          </vxe-column>

          <vxe-column field="transParm1" title="处理取值1" :edit-render="{}">
            <template #edit="{ row, rowIndex, column }">
              <vxe-input v-model="row.transParm1" placeholder="" type="text"></vxe-input>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { isEmpty } from 'lodash';
import SelectDataCheckedList from '@/components/SelectMultDataGrid.vue';
import SelectDataGrid from '@/components/SelectDataGrid.vue';

let instrList: any = reactive([]);
let ruleList: any = reactive([]);
let conKindList: any = reactive([]);
let transKindList: any = reactive([]);
let rloading = ref(false);

let searchForm = reactive({
  instrId: ''
});

onMounted(() => {
  findInstrSetupList();
  getDictItemsList();
});

//批量获取字典(获取对应质控水平)
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['QCConKind', 'QCTransKind'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const conKindType = dictTreeTypeItems.data.find((item) => item.code === 'QCConKind');
  conKindList.push(...conKindType.detailDataList);
  const transKindType = dictTreeTypeItems.data.find((item) => item.code === 'QCTransKind');
  transKindList.push(...transKindType.detailDataList);
}

// 获取左侧仪器下拉选项数据(标题)
function findInstrSetupList() {
  instrList.length = 0; //放入数据前清空数据
  const url = '/lis/instrSetup/getInstrSetupList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { seachValue: '' }
    })
    .then((res: any) => {
      instrList.push(...res.data);
      if (instrList.length > 0) {
        searchForm.instrId = instrList[0].id;
        findConvertRuleList();
      }
    })
    .catch((err: any) => {
      VxeMessage('获取左侧仪器表格数据异常', VxeNotifyType.error);
    });
}
// 获取左侧仪器表格数据+刷新+右侧表格数据
function findConvertRuleList() {
  rloading.value = true;
  ruleList.length = 0; //放入数据前清空数据
  const url = '/api/qc/qcResultConvertRule/findConvertRuleList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { instrId: searchForm.instrId }
    })
    .then((res: any) => {
      ruleList.push(...res.data);
      rloading.value = false;
    })
    .catch((err: any) => {
      rloading.value = false;
      VxeMessage('获取右侧质控项目表格数据异常', VxeNotifyType.error);
    });
}
// 仪器下拉选择 改变
function valueChangeEvent() {
  findConvertRuleList();
}
function addConvertRule() {
  if (isEmpty(searchForm.instrId)) {
    VxeMessage('请选择仪器', VxeNotifyType.error);
  } else {
    const record: any = {
      id: '',
      instrId: searchForm.instrId,
      conKind: '',
      conParm1: '',
      conParm2: '',
      transKind: '',
      transParm1: '',
      transParm2: '',
      itemDictId: '',
      seq: 1,
      orgId: ''
    };
    ruleList.push(record);
  }
}

// 左侧保存
async function saveConvertRuleList() {
  if (isEmpty(searchForm.instrId)) {
    VxeMessage('请选择仪器', VxeNotifyType.error);
  } else {
    let $Xtable = proxy.$refs.convertRuleTableRef;
    if ($Xtable) {
      // 表格实例表用该方法拿到有id的为修改
      const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
        return p.id && p.id !== '';
      });
      // 拿到数组中没有id的数据为新增
      const InsertRecords = ruleList.filter((e: any) => {
        return !e.id || e.id === '';
      });

      const sveOrupdateRules = [] as any[];
      updateRecords.forEach((e: any) => {
        const iIRule: any = {
          id: e.id,
          instrId: e.instrId,
          conKind: e.conKind,
          conParm1: e.conParm1,
          conParm2: e.conParm2,
          transKind: e.transKind,
          transParm1: e.transParm1,
          transParm2: e.transParm2,
          itemDictId: e.itemDictId,
          seq: e.seq,
          orgId: e.orgId
        };

        sveOrupdateRules.push(iIRule);
      });
      InsertRecords.forEach((e: any) => {
        const iIRule: any = {
          id: e.id,
          instrId: e.instrId,
          conKind: e.conKind,
          conParm1: e.conParm1,
          conParm2: e.conParm2,
          transKind: e.transKind,
          transParm1: e.transParm1,
          transParm2: e.transParm2,
          itemDictId: e.itemDictId,
          seq: e.seq,
          orgId: e.orgId
        };
        sveOrupdateRules.push(iIRule);
      });

      if (sveOrupdateRules.length > 0) {
        const url = '/api/qc/qcResultConvertRule/saveOrUpdateConvertRule';
        const obj: any = {};
        obj.qcResultConvertRuleList = sveOrupdateRules;
        proxy.$http
          .post(url, obj)
          .then((res: any) => {
            VxeMessage('更新成功', VxeNotifyType.success);
            setTimeout(() => {
              findConvertRuleList();
            }, 500);
          })
          .catch((err: any) => {
            VxeMessage('更新失败', VxeNotifyType.success);
          });
      } else {
        VxeMessage('无添加或修改数据', VxeNotifyType.error);
      }
    } else {
      return;
    }
  }
}
// 左侧删除
function deleteConvertRule() {
  const sltConvertRules = (proxy.$refs.convertRuleTableRef as any).getCheckboxRecords();
  if (!(sltConvertRules.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delConvertRuleList = sltConvertRules.filter((p: any) => !isEmpty(p.id));
        if (delConvertRuleList.length > 0) {
          const data = { qcResultConvertRuleList: delConvertRuleList };
          const url = '/api/qc/qcResultConvertRule/batchDeleteConvertRuleList';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findConvertRuleList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
        //页面删除未保存的数据
        const removeConvertRuleList = sltConvertRules.filter((p: any) => isEmpty(p.id));
        if (removeConvertRuleList.length > 0) {
          // 删除的新增的空白数据 不走接口
          let $Xtable = proxy.$refs.convertRuleTableRef;
          if ($Xtable) {
            for (const removeRow of removeConvertRuleList) {
              ruleList.splice(removeRow.seq - 1);
            }
          }
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

// 获取组件当前行数据
function selectRow(row, index) {
  ruleList[index].itemDictName = row.itemNa;
  ruleList[index].itemDictId = row.id;
}

function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}
function getItemDictDesc(row) {
  let ItemDIctDesc = '';
  if (!isEmpty(row.itemDictName)) {
    ItemDIctDesc += row.itemDictName;
  }
  if (!isEmpty(row.itemEnCode)) {
    ItemDIctDesc += '[' + row.itemEnCode + ']';
  }
  return ItemDIctDesc;
}
</script>

<style lang="scss" scoped>
#qcResultConvertRuleDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);

    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }

    //右侧质控项目表格
    .tableBox {
      height: calc(100% - 40px);
      background-color: $base-white;
    }
  }
}
</style>
